<script>
import MapDialog from "./components/MapDialog.vue";
import SaveDialog from "./components/SaveDialog.vue";
import KtMap from "/src/components/common/KtMap.vue";
import SensorDialog from "./components/SensorDialog.vue";
import EditorCompont from "./components/EditorCompont.vue";
import iot from "/src/js/iot/index.js";

export default {
  components: { KtMap, SaveDialog, MapDialog, SensorDialog, EditorCompont },
  data() {
    return {
      iot,
      mapLoaded: true,
      bodyData: [],
      deviceArr: [],
      requestParamBind: {
        name: "",
        projectId: "",
      },
      requestParam: {
        deviceId: "",
        description: "",
        sensorName: "",
      },
      contentLoading: true,
      type: "card",
      mapBodyData: {
        center: {
          longitude: 103.8198,
          latitude: 1.3521,
        },
        markers: [
          {
            latitude: 1.3521,
            longitude: 103.8198,
            title: "新加坡",
          },
        ],
      },
      projectList: [],
    };
  },
  async created() {
    await this.getProjectList();
    this.getAll();
  },
  mounted() {},
  methods: {
    getByProjectId() {
      this.$kt.request.send({
        uri: "/business-iot-web/admin/iotDevice/getByProjectId",
        data: { projectId: this.requestParamBind.projectId },
        stateSuccess: (res) => {
          this.deviceArr = res.data;
        },
        stateFail: (err) => {
          this.$message.error(err.errMsg);
        },
      });
    },
    getProjectList() {
      return new Promise((resolve, reject) => {
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotProject/getSelf",
          data: {},
          stateSuccess: (res) => {
            this.projectList = res.data;
            // 默认选择第一个
            if (this.projectList.length > 0) {
              this.requestParamBind.projectId = this.projectList[0].id;
            }
            this.getByProjectId();
            resolve();
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            reject();
          },
        });
      });
    },
    // 初始化mapBodyData
    initMapBodyData() {
      this.mapLoaded = false;
      this.mapBodyData = {
        center: {
          longitude: 103.8198,
          latitude: 1.3521,
        },
        markers: [],
      };
      // 将bodyData中的数据转换为mapBodyData的markers
      this.bodyData.forEach((item) => {
        this.mapBodyData.markers.push({
          latitude: item.latitude,
          longitude: item.longitude,
          title: item.name,
        });
      });
      setTimeout(() => {
        this.mapLoaded = true;
      }, 100);
    },
    toRemove(item) {
      // 是否确定删除,
      this.$confirm(
        this.$i18n.zhToGlobal("是否确定删除？"),
        this.$i18n.zhToGlobal("提示"),
        {
          confirmButtonText: this.$i18n.zhToGlobal("确定"),
          cancelButtonText: this.$i18n.zhToGlobal("取消"),
          type: "warning",
        }
      )
        .then(() => {
          this.contentLoading = true;
          this.$kt.request.send({
            uri: "/business-iot-web/admin/iotDeviceAlarm/remove",
            data: {
              id: item.id,
            },
            stateSuccess: (res) => {
              this.getAll();
              this.contentLoading = false;
            },
            stateFail: (err) => {
              this.$message.error(err.errMsg);
              this.contentLoading = false;
            },
          });
        })
        .catch(() => {});
    },
    toMap(item) {
      this.$refs.mapDialog.open(item.title, {
        center: {
          longitude: item.longitude,
          latitude: item.latitude,
        },
        markers: [
          {
            latitude: item.latitude,
            longitude: item.longitude,
            title: "",
          },
        ],
      });
    },
    getAll() {
      this.contentLoading = true;
      this.$kt.request.send({
        uri: "/business-iot-web/admin/iotDeviceAlarm/getAllNew",
        data: {
          deviceId: this.requestParam.deviceId,
          description: this.requestParam.description,
          sensorName: this.requestParam.sensorName,
          projectId: this.requestParamBind.projectId,
        },
        stateSuccess: (res) => {
          this.contentLoading = false;
          this.bodyData = res.data;
          // 按照优先级排序
          this.bodyData.sort((a, b) => {
            return b.priority - a.priority;
          });
          this.initMapBodyData();
        },
        stateFail: (err) => {
          this.$message.error(err.errMsg);
          this.contentLoading = false;
        },
      });
    },
    selectProject(item) {
      console.log(item);
      this.requestParamBind.projectId = item.id;
      this.requestParam.deviceId = null;
      this.requestParam.description = null;
      this.requestParam.sensorName = null;
      this.getByProjectId();
      this.getAll();
    },
    /**
     * 判断是否在线
     */
    isOnline(item) {
      // 判断最后一次心跳时间是否超过设置的间隔
      if (item.online?.gmtLastHeartbeat) {
        const gmtLastHeartbeat = new Date(
          item.online?.gmtLastHeartbeat
        ).getTime();
        const now = new Date().getTime();
        const interval = item.interval * 1000;
        if (now - gmtLastHeartbeat < interval) {
          return true;
        }
      }
      return false;
    },
  },
};
</script>

<template>
  <div>
    <map-dialog ref="mapDialog"></map-dialog>

    <save-dialog @save="getAll" ref="saveDialog"></save-dialog>
    <editor-compont @save="getAll" ref="editorCompont"></editor-compont>

    <div style="display: inline-block; width: 180px; height: 100vh">
      <div style="font-weight: bold; font-size: 16px; text-align: center">
        {{ $i18n.zhToGlobal("项目列表") }}
      </div>
      <div style="height: 10px"></div>
      <el-scrollbar style="height: calc(100vh - 60px)">
        <div
          style="padding: 10px; box-sizing: border-box"
          v-for="item in projectList"
        >
          <div
            class="card-project"
            :class="{
              'card-project-selected': requestParamBind.projectId === item.id,
            }"
            @click="selectProject(item)"
          >
            {{ item.title }}
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div
      style="
        position: relative;
        display: inline-block;
        width: calc(100vw - 200px);
        margin-left: 10px;
        height: 100vh;
        vertical-align: top;
      "
    >
      <div style="position: relative">
        <el-form @submit.native.prevent>
          <div style="display: flex">
            <el-select
              v-model="requestParam.deviceId"
              @change="getAll"
              :placeholder="$i18n.zhToGlobal('请选择设备')"
              style="width: 200px"
            >
              <el-option
                v-for="item in deviceArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- 在写两个输入框和一个按钮 -->
            <el-input
              v-model="requestParam.description"
              @keyup.enter.native="getAll"
              placeholder="Alarm Description"
              style="width: 200px; margin-left: 10px"
            ></el-input>
            <el-input
              v-model="requestParam.sensorName"
              placeholder="Sensor Name"
              @keyup.enter.native="getAll"
              style="width: 200px; margin-left: 10px"
            ></el-input>
            <!-- 在写两个输入框和一个按钮 -->
            <el-button type="primary" style="margin-left: 10px" @click="getAll">
              <kt-icon
                class="el-icon-search"
                color="#fff"
                @click="getAll"
                icon="el-icon-search"
              >
              </kt-icon>
            </el-button>
          </div>
        </el-form>

        <div style="position: absolute; right: 0; top: 0">
          <!-- 刷新 -->
          <el-button type="primary" @click="getAll">
            <kt-icon
              class="el-icon-refresh"
              color="#fff"
              @click="getAll"
              icon="el-icon-refresh"
            >
            </kt-icon>
          </el-button>

          <el-button
            type="primary"
            @click="$refs.saveDialog.openNew(requestParamBind.projectId)"
          >
            <kt-icon class="icon-add" color="#fff" icon="el-icon-plus">
            </kt-icon>
          </el-button>
        </div>
      </div>

      <el-scrollbar
        v-if="type === 'card'"
        v-loading="contentLoading"
        class="scrollbar-box"
      >
        <!-- 更改头部颜色 -->
        <el-table
          :data="bodyData"
          style="width: 100%"
          border
          height="calc(100vh - 120px)"
        >
          <el-table-column
            :label="$i18n.zhToGlobal('Serial no')"
            prop="id"
          >
          </el-table-column>
          <el-table-column
            prop="description"
            :label="$i18n.zhToGlobal('Name')"
          >
          </el-table-column>

          <!-- 是否在线 -->
          <el-table-column
            prop="sensorId"
            :label="$i18n.zhToGlobal('Linked sensors')"
            width="200"
          >
            <!-- <template #default="scope">
              <el-tag v-if="isOnline(scope.row)" type="success">
                {{ $i18n.zhToGlobal("在线") }}
              </el-tag>
              <el-tag v-else type="danger">
                {{ $i18n.zhToGlobal("离线") }}
              </el-tag>
            </template> -->
          </el-table-column>

          <el-table-column
            prop="type"
            :label="$i18n.zhToGlobal('Trigged condition')"
            width="200"
          >
          </el-table-column>

          <el-table-column
            :label="$i18n.zhToGlobal('Data parameter')"
            width="180"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.x">x = {{ scope.row.x }} </el-tag>
              <el-tag v-if="scope.row.y">y = {{ scope.row.y }} </el-tag>
              <el-tag v-if="scope.row.m">m = {{ scope.row.m }} </el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="name"
            :label="$i18n.zhToGlobal('Execution type')"
            width="180"
          >
          </el-table-column> -->
          <el-table-column
            prop="isEnable"
            :label="$i18n.zhToGlobal('Status')"
            width="180"
          >
          <template #default="scope">
              <div style="text-align: center">
                <div v-if="scope.row.isEnable">
                  Normal
                </div>
                <div v-else>
                  Pause
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            :label="$i18n.zhToGlobal('Action')"
            width="180"
          >
            <template #header>
              <div style="text-align: center">
                {{ $i18n.zhToGlobal("Action") }}
              </div>
            </template>
            <template #default="scope">
              <div style="text-align: center">
                <div>
                  <kt-icon
                    @click="$refs.editorCompont.openNew(requestParamBind.projectId, scope.row)"
                    icon="ant-icon-edit-outlined"
                    color="#000"
                    class="icon-edit icon-btn"
                  ></kt-icon>
                  <kt-icon
                    @click="toRemove(scope.row)"
                    icon="el-icon-delete"
                    color="#ff0000"
                    style="margin-left: 20px"
                    class="icon-delete icon-btn"
                  ></kt-icon>
                </div>
                <!-- <div>
                  <el-button
                    @click="() => this.$refs.sensorDialog.open(scope.row.id)"
                    >{{ $i18n.zhToGlobal("传感器列表") }}</el-button
                  >
                </div> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="false" class="card" v-for="item in bodyData">
          <div class="card-header">
            <div class="card-title">
              {{ item.title }}
              <span class="card-sn">#{{ item.sn }}</span>
            </div>
          </div>
          <div class="card-body">
            <div class="card-text">
              <el-scrollbar class="scrollbar">
                <div>{{ item.description }}</div>
              </el-scrollbar>
            </div>
            <div class="card-lon-lat" @click="toMap(item)">
              <kt-icon
                icon="ant-icon-compass-outlined"
                color="#000"
                style="vertical-align: bottom"
              ></kt-icon>
              {{ item.longitude }} , {{ item.latitude }}
            </div>
            <div style="position: absolute; bottom: 15px; right: 10px">
              <kt-icon
                @click="() => this.$refs.saveDialog.open(item)"
                icon="ant-icon-edit-outlined"
                color="#000"
                class="icon-edit icon-btn"
              ></kt-icon>
              <kt-icon
                style="margin-left: 10px"
                color="#ff0000"
                icon="el-icon-delete"
                class="icon-delete icon-btn"
                @click="toRemove(item)"
              ></kt-icon>
            </div>
          </div>
        </div>
      </el-scrollbar>

      <div class="map-box" v-if="type === 'map'">
        <kt-map v-if="mapLoaded" :data="mapBodyData"></kt-map>
      </div>

    </div>

    <sensor-dialog ref="sensorDialog"></sensor-dialog>
  </div>
</template>

<style scoped lang="scss">
.card {
  position: relative;
  margin: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  width: 300px;
  display: inline-block;

  .card-header {
    padding: 10px;
    border-bottom: 1px solid #e8e8e8;

    .card-title {
      font-size: 16px;
      font-weight: bold;

      .card-sn {
        font-size: 12px;
        font-weight: lighter;
        margin-left: 10px;
        float: right;
      }
    }
  }

  .card-body {
    padding: 10px;

    .card-text {
      font-size: 14px;
    }
  }
}

.scrollbar {
  height: 100px;
  overflow: auto;
  padding: 10px;

  .el-scrollbar__wrap {
    padding: 0;
  }

  .el-scrollbar__view {
    padding: 0;
  }

  .el-scrollbar__bar {
    background-color: #e8e8e8;
  }

  .el-scrollbar__thumb {
    background-color: #999;
  }
}

.card-lon-lat {
  font-size: 12px;
  font-weight: lighter;
  padding: 10px;
  cursor: pointer;
}

.card-lon-lat:hover {
  opacity: 0.6;
}

.card-lon-lat:active {
  opacity: 1;
}

.icon-edit {
  cursor: pointer;
}

.icon-delete {
  cursor: pointer;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn:active {
  transform: scale(1);
}

.scrollbar-box {
  height: calc(100vh - 120px);
  padding: 10px;
  text-align: center;
}

.bottom {
  position: absolute;
  bottom: 10px;
  display: flex;
}

.pagination {
  margin-left: 280px;
}

.map-box {
  width: 100%;
  height: calc(100vh - 120px);
  border-radius: 5px;
  overflow: hidden;
}

.card-project {
  padding: 10px;
  cursor: pointer;
  background-color: #f8f8f8;
  border-radius: 20px;
  text-align: center;
}

.card-project-selected {
  background-color: #333;
  color: #fff;
}
</style>